package main

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"
)

func main() {
	var tip string
	library := make(map[string]map[string]string)

	// 读取或创建文件
	if _, err := os.Stat("library.json"); os.IsNotExist(err) {
		library = make(map[string]map[string]string)
	} else {
		data, err := os.ReadFile("library.json")
		if err != nil {
			fmt.Println("读取文件失败：", err)
			return
		}
		err = json.Unmarshal(data, &library)
		if err != nil {
			fmt.Println("解析JSON失败：", err)
			return
		}
	}

	for {
		fmt.Print("请输入你的选择(1.注册, 2.登录, 3.退出):")
		fmt.Scanln(&tip)
		tip = strings.TrimSpace(tip)

		switch tip {
		case "1":
			fmt.Print("你选择的是注册,请输入用户名:")
			var username string
			fmt.Scanln(&username)
			username = strings.TrimSpace(username)

			if _, exists := library[username]; exists {
				fmt.Println("用户名已经存在,无法注册")
				continue
			}
			fmt.Print("请输入密码:")
			var passwd string
			fmt.Scanln(&passwd)
			fmt.Print("请输入年龄:")
			var age string
			fmt.Scanln(&age)
			fmt.Print("请输入性别:")
			var sex string
			fmt.Scanln(&sex)

			userInfo := map[string]string{
				"passwd": passwd,
				"age":    age,
				"sex":    sex,
			}
			library[username] = userInfo
			libraryJSON, err := json.MarshalIndent(library, "", "  ")
			if err != nil {
				fmt.Println("序列化JSON失败：", err)
				return
			}
			err = os.WriteFile("library.json", libraryJSON, 0644)
			if err != nil {
				fmt.Println("写入文件失败：", err)
				return
			}
			fmt.Println("注册成功")

		case "2":
			fmt.Print("你选择的是登录,请输入用户名:")
			var username string
			fmt.Scanln(&username)
			username = strings.TrimSpace(username)

			if _, exists := library[username]; !exists {
				fmt.Println("用户名输入错误")
				continue
			}
			fmt.Print("请输入密码:")
			var passwd1 string
			fmt.Scanln(&passwd1)

			if passwd1 == library[username]["passwd"] {
				fmt.Println("登录成功")
				break
			} else {
				fmt.Println("密码错误, 登录失败")
			}

		case "3":
			break

		default:
			fmt.Println("请输入1或者2或者3")
		}
	}
}
